//
//  LKImagePickerView.m
//  LKImagePickerDemo
//
//  Created by LIUKUN-PC on 16/5/31.
//  Copyright © 2016年 liukun. All rights reserved.
//

#import "LKImagePickerView.h"
#import "LKImagePickerManager.h"
#import "UIViewController+LKCurrentViewController.h"

@class LKImagePickerCollectionViewCell;

@interface LKImagePickerView ()<UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;

//图片
@property (nonatomic, strong) NSMutableArray<UIImage *> *photos;

//记录相册里已选的Asset
@property (nonatomic, strong) NSMutableArray<PHAsset *> *assets;

//从相册里选择的是否是原图
@property (nonatomic, assign) BOOL isSelectOriginalPhoto;

//图片选择管理器
@property (nonatomic, strong) LKImagePickerManager *imagePickerManager;



//回调
@property (nonatomic, copy) void(^selectedImageCountDidChangeBlock)(NSInteger imageCount, NSInteger itemCount, CGFloat bestHeightWidthRatio);

@end

@implementation LKImagePickerView

static NSString * const reusedCellID = @"ImagePickerCollectionCell";

#pragma mark - API

-(void)selectedImageCountDidChangeHandler:(void (^)(NSInteger, NSInteger, CGFloat))selectedImageCountDidChangeBlock {
    
    self.selectedImageCountDidChangeBlock = selectedImageCountDidChangeBlock;
}


+ (instancetype)imagePickerViewWithFrame:(CGRect)frame currentViewController:(UIViewController *)currentViewController {
    
    LKImagePickerView *imagePickerView = [[LKImagePickerView alloc] initWithFrame:frame];
    imagePickerView.currentViewController = currentViewController;
    return imagePickerView;
}

#pragma mark - inits

- (instancetype)init {
    if (self = [super init]) {
        [self initSubViews];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self initSubViews];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initSubViews];
    }
    return self;
}

- (void)initSubViews {
    
    _maxCountAtSingleLine = 3;
    _maxImageCount = 9;
    _sourceType = LKImagePickerSourceTypeAll;
    
    
    _flowLayout = [[UICollectionViewFlowLayout alloc] init];
    _flowLayout.minimumLineSpacing = 0;
    _flowLayout.minimumInteritemSpacing = 0;

    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) collectionViewLayout:_flowLayout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    [_collectionView registerClass:[LKImagePickerCollectionViewCell class] forCellWithReuseIdentifier:reusedCellID];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [self addSubview:_collectionView];
    

}

- (void)layoutSubviews {
    
    _collectionView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
}


#pragma mark - <UICollectionViewDataSource>


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    self.itemCount = self.photos.count + (self.photos.count != self.maxImageCount);
    
    return self.itemCount;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    LKImagePickerCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reusedCellID forIndexPath:indexPath];
    if (indexPath.item == self.photos.count && self.photos.count < self.maxImageCount) {
        cell.imageView.image = [UIImage imageNamed:@"AlbumAddBtn.png"];

        cell.deleteBlock = nil;
        
    } else {
        cell.imageView.image = self.photos[indexPath.item];
        __weak typeof(self) weakSelf = self;
        cell.deleteBlock = ^{
            [weakSelf.photos removeObjectAtIndex:indexPath.row];
            [weakSelf.assets removeObjectAtIndex:indexPath.row];
            [weakSelf.collectionView reloadData];
            weakSelf.itemCount -= 1;
            
        };
    }
    return cell;
}

#pragma mark - <UICollectionViewDelegate>

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    __weak typeof(self) weakSelf = self;
    __weak LKImagePickerManager *weakImagePickerManager = self.imagePickerManager;
    
    LKPickImagesFinishedBlock didFinishPickingPhotosBlock = ^(NSArray<UIImage *> *photos, NSArray<PHAsset *> *assets, BOOL isSelectOriginalPhoto, BOOL isFromCamera) {
        if (isFromCamera) {
            [weakSelf.photos addObjectsFromArray:photos];
            [weakSelf.assets addObjectsFromArray:assets];
            
        } else {
            weakSelf.photos = [photos mutableCopy];
            weakSelf.assets = [assets mutableCopy];
            
        }
        weakSelf.isSelectOriginalPhoto = isSelectOriginalPhoto;
        
        [weakSelf.collectionView reloadData];
    };
    
    if (indexPath.item == self.photos.count && self.photos.count < self.maxImageCount) {
        
        

        //添加图片
        if (self.sourceType == LKImagePickerSourceTypeAll) {
            //拍照和从相册里选择
            
            [self.imagePickerManager showImagesPickerSheetViewWithSelectedAssets:self.assets isSelectOriginalPhoto:self.isSelectOriginalPhoto maxImagesCount:self.maxImageCount didFinishPickingPhotosHandler:didFinishPickingPhotosBlock];
        } else if (self.sourceType == LKImagePickerSourceTypeCamera) {
            //拍照
            [self.imagePickerManager openCameraWithIsSelectOriginalPhoto:self.isSelectOriginalPhoto takePhotosDidFinishHandler:didFinishPickingPhotosBlock];
        } else {
            //从相册里选择
            [self.imagePickerManager pickPhotosWithSelectedAssets:self.assets isSelectOriginalPhoto:self.isSelectOriginalPhoto maxImagesCount:self.maxImageCount didFinishPickingPhotosHandler:didFinishPickingPhotosBlock];
        }
    } else {
        //预览图片
        [self.imagePickerManager previewPhotosWithSelectedAssets:self.assets selectedPhotos:self.photos index:indexPath.row isSelectOriginalPhoto:self.isSelectOriginalPhoto didChangeSelectedAssetHandler:didFinishPickingPhotosBlock];
    }
}

#pragma mark - UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat width = collectionView.frame.size.width / self.maxCountAtSingleLine;
    return CGSizeMake(width, width);
}

#pragma mark - Getter & Setter

- (LKImagePickerManager *)imagePickerManager {
    if (!_imagePickerManager) {
        _imagePickerManager = [LKImagePickerManager imagePickerManagerWithCurrentViewController:self.currentViewController];
    }
    return _imagePickerManager;
}

- (NSMutableArray<UIImage *> *)photos {
    if (!_photos) {
        _photos = [NSMutableArray<UIImage *> array];
    }
    return _photos;
}

- (NSMutableArray<PHAsset *> *)assets {
    if (!_assets) {
        _assets = [NSMutableArray<PHAsset *> array];
    }
    return _assets;
}

- (void)setItemCount:(NSInteger)itemCount {
    if (_itemCount == itemCount && itemCount != self.maxImageCount) {
        return;
    }
    _itemCount = itemCount;
    if (self.selectedImageCountDidChangeBlock) {
        self.selectedImageCountDidChangeBlock(self.photos.count, _itemCount, ceil(_itemCount * 1.0 / self.maxCountAtSingleLine) / self.maxCountAtSingleLine);
    }
}

- (UIViewController *)currentViewController {
    if (!_currentViewController) {
        _currentViewController = [UIViewController currentViewController];
    }
    return _currentViewController;
}


@end

//间隔
static const CGFloat kSpace = 5;
static const CGFloat kButtonLenght = 20;

@interface LKImagePickerCollectionViewCell ()

@property (nonatomic, strong) UIButton *deleteButton;

@end


@implementation LKImagePickerCollectionViewCell


- (instancetype)init {
    if (self = [super init]) {
        [self initSubViews];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initSubViews];
    }
    return self;
}

- (void)initSubViews {
    self.backgroundColor = [UIColor whiteColor];
    _imageView = [[UIImageView alloc] init];
    _imageView.backgroundColor = [UIColor colorWithWhite:1.000 alpha:0.500];
    _imageView.contentMode = UIViewContentModeScaleAspectFill;
    [self.contentView addSubview:_imageView];
    _imageView.clipsToBounds = YES;
    
    self.deleteButton = [[UIButton alloc] init];
    [self.deleteButton addTarget:self action:@selector(deleteAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.deleteButton setImage:[UIImage imageNamed:@"lk_image_picker_delete"] forState:UIControlStateNormal];
    self.deleteButton.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    self.deleteButton.hidden = YES;
    
    self.deleteButton.layer.cornerRadius = kButtonLenght / 2;
    self.deleteButton.layer.masksToBounds = YES;
    
    self.deleteButton.imageEdgeInsets = UIEdgeInsetsMake(3, 3, 3, 3);
    
    [self addSubview:self.deleteButton];
}


- (void)layoutSubviews {
    
    
    _imageView.frame = CGRectMake(kSpace, kSpace, self.contentView.frame.size.width - 2 * kSpace, self.contentView.frame.size.height - 2 * kSpace);
    _deleteButton.frame = CGRectMake(CGRectGetMaxX(_imageView.frame) - kButtonLenght, CGRectGetMinY(_imageView.frame), kButtonLenght, kButtonLenght);
}

- (void)deleteAction:(UIButton *)sender {
    if (self.deleteBlock) {
        self.deleteBlock();
    }
}

- (void)setDeleteBlock:(void (^)())deleteBlock {
    _deleteBlock = deleteBlock;
    
    self.deleteButton.hidden = _deleteBlock == nil;
    
}



@end
